// pages/spellGroupDetails/spellGroupDetails.js
const app = getApp()
var http = require('../../utils/http.js');
var config = require('../../utils/config.js');
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hideModal: true,
    groupTempInfo: {},
    groupUserList: [],
    countDownObj: {},
    countDownTimeout: null,
    nowTime: new Date().getTime(),
    skuShow: false,
    prodNum: 1,
    skuList: [],
    skuGroup: {},
    findSku: true,
    defaultSku: undefined,
    detaultGroupSku: undefined,
    selectedProp: [],
    selectedPropObj: {},
    selectedProperties: "",
    propKeys: [],
    allProperties: [],
    groupTeamId: '',
    groupSkuId: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let groupTeamId = options.groupTeamId || ''
    let orderNumber = options.orderNumber || ''
    this.getGroupTeamInfo(groupTeamId, orderNumber)
  },

  //根据sku的属性 分组
  groupSkuProp: function(skuList) {
    // var skuList = this.data.skuList;
    if (skuList.length == 1 && skuList[0].properties == "") {
      this.setData({
        defaultSku: skuList[0]
      });
      return;
    }
    var skuGroup = {};
    var allProperties = [];
    var propKeys = [];
    this.setData({
      selectedPropObj: {}
    });

    for (var i = 0; i < skuList.length; i++) {
      var defaultSku = this.data.defaultSku;
      var isDefault = false;
      if (!defaultSku && skuList[i].actPrice == this.data.groupTempInfo.groupProd.actPrice) { //找到和商品价格一样的那个SKU，作为默认选中的SKU
        defaultSku = skuList[i];
        isDefault = true;
        this.setData({
          defaultSku: defaultSku
        });
      }

      var properties = skuList[i].properties; //版本:公开版;颜色:金色;内存:64GB
      allProperties.push(properties);
      var propList = properties.split(";"); // ["版本:公开版","颜色:金色","内存:64GB"]

      var selectedPropObj = this.data.selectedPropObj;
      for (var j = 0; j < propList.length; j++) {

        var propval = propList[j].split(":"); //["版本","公开版"]
        var props = skuGroup[propval[0]]; //先取出 版本对应的值数组

        //如果当前是默认选中的sku，把对应的属性值 组装到selectedProp
        if (isDefault) {
          propKeys.push(propval[0]);
          selectedPropObj[propval[0]] = propval[1];
        }

        if (props == undefined) {
          props = []; //假设还没有版本，新建个新的空数组
          props.push(propval[1]); //把 "公开版" 放进空数组
        } else {
          if (!this.array_contain(props, propval[1])) { //如果数组里面没有"公开版"
            props.push(propval[1]); //把 "公开版" 放进数组
          }
        }
        skuGroup[propval[0]] = props; //最后把数据 放回版本对应的值
      }
      this.setData({
        selectedPropObj: selectedPropObj,
        propKeys: propKeys
      });
    }
    this.parseSelectedObjToVals();
    this.setData({
      skuGroup: skuGroup,
      allProperties: allProperties
    });
  },

  //将已选的 {key:val,key2:val2}转换成 [val,val2]
  parseSelectedObjToVals: function() {
    var selectedPropObj = this.data.selectedPropObj;
    var selectedProperties = "";
    var selectedProp = [];
    for (var key in selectedPropObj) {
      selectedProp.push(selectedPropObj[key]);
      selectedProperties += key + ":" + selectedPropObj[key] + ";";
    }
    selectedProperties = selectedProperties.substring(0, selectedProperties.length - 1);
    this.setData({
      selectedProp: selectedProp,
      selectedProperties: selectedProperties
    });

    var findSku = false;
    for (var i = 0; i < this.data.skuList.length; i++) {
      if (this.data.skuList[i].properties == selectedProperties) {
        findSku = true;
        this.setData({
          defaultSku: this.data.skuList[i]
        });
        break;
      }
    }
    this.setData({
      findSku: findSku
    });
  },

  //点击选择规格
  toChooseItem: function(e) {
    var ok = e.currentTarget.dataset.ok;
    if (!ok) {
      return;
    }
    var val = e.currentTarget.dataset.val;
    var key = e.currentTarget.dataset.key;
    var selectedPropObj = this.data.selectedPropObj;
    selectedPropObj[key] = val;
    this.setData({
      selectedPropObj: selectedPropObj
    });
    console.log(this.data.selectedPropObj)
    this.parseSelectedObjToVals();
  },

  //判断数组是否包含某对象
  array_contain: function(array, obj) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] == obj) //如果要求数据类型也一致，这里可使用恒等号===
        return true;
    }
    return false;
  },

  /**
   * 减数量
   */
  onCountMinus: function() {
    var prodNum = this.data.prodNum;
    if (prodNum > 1) {
      this.setData({
        prodNum: prodNum - 1
      });
    }
  },

  /**
   * 加数量
   */
  onCountPlus: function() {
    var prodNum = this.data.prodNum;
    if (prodNum < 1000) {
      this.setData({
        prodNum: prodNum + 1
      });
    }
  },

  /**
   * 参团
   */
  groupConfirmOrder: function() {
    if (!this.data.findSku) {
      return;
    }
    wx.setStorageSync("groupOrderItem", JSON.stringify({
      groupSkuId: this.data.defaultSku.groupSkuId,
      groupTeamId: this.data.groupTeamId,
      prodCount: this.data.prodNum
    }));
    wx.navigateTo({
      url: '/pages/groupConfirmOrder/groupConfirmOrder',
    })
  },

  // 提交订单
  commitOrder() {
    wx.showLoading()
    var orderShopParam = {
      remarks: "",
    }
    http.request({
      url: `/p/group/order/submit`,
      method: 'POST',
      data: orderShopParam,
      callBack: (res) => {
        this.calWeixinPay(res.orderNumbers)
      }
    })
  },
  /**
   * 唤起微信支付
   */
  calWeixinPay: function(orderNumbers) {
    wx.showLoading({
      mask: true
    });
    var params = {
      url: "/p/order/pay",
      method: "POST",
      data: {
        payType: 1,
        orderType: 1,
        orderNumbers: orderNumbers
      },
      callBack: (res) => {
        wx.hideLoading();
        wx.requestPayment({
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          package: res.packageValue,
          signType: res.signType,
          paySign: res.paySign,
          success: e => {
            wx.showModal({
              title: '支付成功',
              content: '',
              showCancel: false,
              success: () => {
                wx.navigateTo({
                  url: '/pages/spellGroupDetails/spellGroupDetails?orderNumber=' + orderNumbers,
                })
              }
            })

          },
          fail: err => {
            wx.navigateTo({
              url: '/pages/pay-result/pay-result?sts=0&orderNumbers=' + orderNumbers + "&orderType=" + this.data.orderType,
            })
          }
        })

      }
    };
    http.request(params);
  },

  /**
   * 去地址页面
   */
  toAddrListPage: function() {
    wx.navigateTo({
      url: '/pages/delivery-address/delivery-address?order=0',
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearTimeout(this.data.countDownTimeout)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  showSku: function() {
    this.setData({
      skuShow: true
    });
  },

  closePopup: function() {
    this.setData({
      skuShow: false
    });
  },

  /**
   * 加载拼团团队详情
   */
  getGroupTeamInfo: function(groupTempId, orderNumber) {
    let _this = this
    http.request({
      url: "/p/groupTeam/info",
      method: "GET",
      data: {
        groupTeamId: groupTempId,
        orderNumber: orderNumber
      },
      callBack: (res) => {
        console.log(res)
        _this.setData({
          skuList: res.groupSkuList,
          groupTempInfo: res,
          groupUserList: res.apiGroupUserList,
          nowTime: util.dateToTimestamp(res.groupTeam.nowTime),
          joinNum: res.groupTeam.groupNumber - 1,
          groupTeamId: res.groupTeam.groupTeamId
        })
        let groupUserCount = _this.data.groupUserList.length
        let groupNumber = _this.data.groupTempInfo.groupTeam.groupNumber
        let unGroupNumber = groupNumber - groupUserCount
        let groupUserList = _this.data.groupUserList
        if (unGroupNumber > 0) {
          for (let i = 0; i < unGroupNumber; i++) {
            groupUserList = groupUserList.concat({})
          }
        }
        _this.setData({
          groupUserList: groupUserList
        })
        _this.countdown();
        _this.groupSkuProp(res.groupSkuList);
      }
    })
  },
  // 倒计时
  countdown() {
    // 获取当前时间，同时得到活动结束时间数组
    let nowTime = this.data.nowTime;
    let endTime = util.dateToTimestamp(this.data.groupTempInfo.groupTeam.endTime);
    let countDownObj = {};
    // 对结束时间进行处理渲染到页
    if (endTime - nowTime > 0) {
      // 如果活动未结束，对时间进行处理
      let time = (endTime - nowTime) / 1000;
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 24) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      countDownObj = {
        day: `${this.timeFormat(day)}`,
        hou: `${this.timeFormat(hou)}`,
        min: `${this.timeFormat(min)}`,
        sec: `${this.timeFormat(sec)}`,
      }
    } else {
      countDownObj = {
        day: '00',
        hou: '00',
        min: '00',
        sec: '00'
      }
    }

    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({
      nowTime: nowTime + 1000,
      countDownObj: countDownObj,
      countDownTimeout: setTimeout(this.countdown, 1000)
    })
  },
  // 小于10的格式化函数
  timeFormat(times) {
    return times < 10 ? '0' + times : times;
  },
  /**
   * 查看订单详情
   */
  toOrderDetailPage: function(e) {
    wx.navigateTo({
      url: '/pages/order-detail/order-detail?orderNum=' + e.currentTarget.dataset.ordernum,
    })
  },
  /**
   * 查看拼团团队
   */
  toGroupTempInfoPage: function(e) {
    wx.navigateTo({
      url: '/pages/spellMembersDetails/spellMembersDetails?groupTeamId=' + e.currentTarget.dataset.groupteamid,
    })
  },
  /**
   * 用户点击转发
   */
  onShareAppMessage: function(res) {
    return {
      title: this.data.groupTempInfo.groupProd.prodName,
      path: '/pages/spellGroupDetails/spellGroupDetails?groupTeamId=' + this.data.groupTempInfo.groupTeam.groupTeamId,
      imageUrl: this.data.groupTempInfo.groupProd.pic
    }
  },

})